{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Course Prerequisites\n",
    "\n",
    "[The Original Question](https://mp.weixin.qq.com/s/O_iow_KloLeLZml8Ca8iGw)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Question\n",
    "\n",
    "You are given a hash table where the key is a course code, and the value is a list of all the course codes that are prerequisites for the key. Return a valid ordering in which we can complete the courses. If no such ordering exists, return NULL."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Example\n",
    "\n",
    "```{python}\n",
    "{\n",
    "    'CSC300': ['CSC100', 'CSC200'],\n",
    "    'CSC200': ['CSC100'],\n",
    "    'CSC100': []\n",
    "}\n",
    "```\n",
    "\n",
    "This input should return the order that we need to take these courses:\n",
    "\n",
    "```{python}\n",
    "['CSC100', 'CSC200', 'CSC300']\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['A101', 'A102', 'A103']\n"
     ]
    }
   ],
   "source": [
    "def courses_to_take(courses_to_prereqs: dict):\n",
    "    array = list()\n",
    "    length = len(array)\n",
    "    # Find the course which needs no dependencies\n",
    "    while len(courses_to_prereqs.keys()) != 0:\n",
    "        for k in courses_to_prereqs.keys():\n",
    "            if len(courses_to_prereqs[k]) == 0:\n",
    "                array.append(k)\n",
    "                courses_to_prereqs.pop(k)\n",
    "                break\n",
    "            pass\n",
    "        if len(array) == length:\n",
    "            return 'NULL'\n",
    "        length = len(array)\n",
    "        for k in courses_to_prereqs:\n",
    "            try:\n",
    "                courses_to_prereqs[k].remove(array[-1])\n",
    "                pass\n",
    "            except ValueError:\n",
    "                pass\n",
    "            pass\n",
    "        pass\n",
    "    return array\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    courses = {\n",
    "        'A101': [],\n",
    "        'A102': ['A101'],\n",
    "        'A103': ['A101', 'A102']\n",
    "    }\n",
    "    print(courses_to_take(courses))\n",
    "    pass"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
